
const fs = require('fs');
const http = require('http');
const path = require('path');
const config = require('./config');

const citiesFileName = path.join(process.cwd(), 'cities.json');


if (!fs.existsSync(citiesFileName)) {
    
        let areaApi = 'http://' + config.apiHost + ':' + config.apiPort + '/api/area?level=2';
    
        console.log( areaApi);
    
        http.get(areaApi, (res) => {
    
            if (res.statusCode === 200) {
                let rawData = '';
    
                res.on('data', (chunk) => rawData += chunk);
                res.on('end', () => {
                    try {
                        const parsedData = JSON.parse(rawData);
                        console.log(parsedData.list);
                        if (parsedData.list) {
                            fs.writeFileSync(citiesFileName, JSON.stringify(parsedData.list));
                            console.log('write file sucessful!');
                        }
                        else {
                            console.log('write file err!');
                        }
    
                    } catch (e) {
                        console.log(e.message);
                    }
                });
            }
        });
    }
    